//
//  LoginVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/11.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "LoginVC.h"

@interface LoginVC ()<UITextFieldDelegate>
{
    dispatch_source_t _timer;
    BOOL _isSMSon;
}
@property (strong, nonatomic) UIButton *SMSLogin;

@property (strong, nonatomic) UIButton *clearBtn;
@property (strong, nonatomic) UIButton *hiddenON;
@property (strong, nonatomic) UIButton *login;
@property (strong, nonatomic) UITextField *userName;
@property (strong, nonatomic) UITextField *password;

@end

@implementation LoginVC

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
   [self setNavTitle:@"短信验证登录" titleColor:[UIColor whiteColor] font:font17];
    
    self.view.backgroundColor = [UIColor whiteColor];
//    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
//    
//    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    
    [self.navigationController.navigationBar setBackgroundImage:
     [UIImage imageNamed:@"logain_nav_bg_default.png"] forBarMetrics:UIBarMetricsDefault];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [self initView];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    if(_timer!=nil){
       dispatch_source_cancel(_timer);
    }    
}


- (void)initView{
    UIImageView *titltImg = [[UIImageView alloc] init];
    titltImg.image = [UIImage imageNamed:@"login_icon_default_nor.png"];
    [self.view addSubview:titltImg];
    titltImg.sd_layout
    .topSpaceToView(self.view, GETHEIGHT(172))
    .centerXEqualToView(self.view)
    .widthIs(GETWITH(140))
    .heightEqualToWidth();
    
    UIImageView *userImg = [[UIImageView alloc] init];
    userImg.image = [UIImage imageNamed:@"login_icon1_input_nor.png"];
    [self.view addSubview:userImg];
    userImg.sd_layout
    .topSpaceToView(titltImg, GETHEIGHT(180))
    .leftSpaceToView(self.view, GETWITH(40))
    .widthIs(GETWITH(42))
    .heightIs(GETHEIGHT(46));
    
    _userName = [[UITextField alloc] init];
    _userName.font = [UIFont systemFontOfSize:16*H];
    _userName.textColor = UIColorFromRGB(0x333333);
    _userName.delegate = self;
    _userName.returnKeyType = UIReturnKeyDone;
    _userName.placeholder = @"请输入手机号码";
    [self.view addSubview:_userName];
    _userName.sd_layout
    .leftSpaceToView(userImg, GETWITH(46))
    .centerYEqualToView(userImg)
    .rightSpaceToView(self.view, GETWITH(130))
    .heightIs(GETHEIGHT(60));
    
    _clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_clearBtn setImage:[UIImage imageNamed:@"login_icon3_input_nor"] forState:UIControlStateNormal];
    [_clearBtn addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_clearBtn];
    _clearBtn.sd_layout
    .rightSpaceToView(self.view, GETWITH(52))
    .centerYEqualToView(userImg)
    .widthIs(GETWITH(40))
    .heightEqualToWidth();
    
    UIView *fgView = [[UIView alloc] init];
    fgView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:fgView];
    fgView.sd_layout
    .leftEqualToView(userImg)
    .rightSpaceToView(self.view, GETWITH(40))
    .topSpaceToView(_userName, GETHEIGHT(27))
    .heightIs(GETHEIGHT(1));
    
    
    UIImageView *suoImg = [[UIImageView alloc] init];
    suoImg.image = [UIImage imageNamed:@"login_icon2_input_nor"];
    [self.view addSubview:suoImg];
    suoImg.sd_layout
    .leftEqualToView(userImg)
    .topSpaceToView(fgView, GETHEIGHT(50))
    .widthIs(GETWITH(42))
    .heightIs(GETHEIGHT(46));
    
    _password = [[UITextField alloc] init];
    _password.font = [UIFont systemFontOfSize:16*H];
    _password.textColor = UIColorFromRGB(0x333333);
    _password.placeholder = @"请输入密码";
    _password.delegate = self;
    _password.returnKeyType = UIReturnKeyDone;
    [self.view addSubview:_password];
    _password.sd_layout
    .leftSpaceToView(suoImg, GETWITH(46))
    .centerYEqualToView(suoImg)
    .rightSpaceToView(self.view, GETWITH(280))
    .heightIs(GETHEIGHT(60));
    
    _hiddenON = [UIButton buttonWithType:UIButtonTypeCustom];
   
    [_hiddenON addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];
    [_hiddenON setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_hiddenON setTitleColor:UIColorFromRGB(0xe64463) forState:UIControlStateNormal];
    _hiddenON.backgroundColor = [UIColor whiteColor];
    _hiddenON.titleLabel.font = font14;
    
    [self.view addSubview:_hiddenON];
    _hiddenON.sd_layout
    .rightEqualToView(fgView)
    .centerYEqualToView(suoImg)
    .widthIs(GETWITH(204))
    .heightIs(GETHEIGHT(56));
    _hiddenON.layer.borderWidth = 1;
    _hiddenON.layer.borderColor = UIColorFromRGB(0xe64463).CGColor;
    _hiddenON.sd_cornerRadius = @(GETHEIGHT(28));
    
    UIView *fView = [[UIView alloc] init];
    fView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:fView];
    fView.sd_layout
    .leftEqualToView(suoImg)
    .rightEqualToView(_hiddenON)
    .topSpaceToView(_password, GETHEIGHT(28))
    .heightIs(GETHEIGHT(1));
    
    __weak typeof(self) weakself = self;
    CGFloat Widh = 0;
    CGFloat height = 0;
    _SMSLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    [_SMSLogin setTitleColor:UIColorFromRGB(0xe64463) forState:UIControlStateNormal];
    [_SMSLogin setTitle:@"账号密码登录" forState:UIControlStateNormal];
    [_SMSLogin handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakself.navigationController popViewControllerAnimated:YES];
    }];

    Widh = [ToolClass heighW:font12 titleStr:@"账号密码登录"].width;
    height = [ToolClass heighW:font12 titleStr:@"账号密码登录"].height;
    _SMSLogin.titleLabel.font = font12;
    [self.view addSubview:_SMSLogin];
    _SMSLogin.sd_layout
    .leftEqualToView(fView)
    .topSpaceToView(fView, GETHEIGHT(20))
    .widthIs(Widh)
    .heightIs(height);
    
    
    _login = [UIButton buttonWithType:UIButtonTypeCustom];
    [_login setBackgroundImage:[UIImage imageNamed:@"login_btn_defauit_nor"] forState:UIControlStateNormal];
    [_login addTarget:self action:@selector(ONLogin:) forControlEvents:UIControlEventTouchUpInside];
   // _login.enabled = NO;
    [self.view addSubview:_login];
    _login.sd_layout
    .topSpaceToView(fView, GETHEIGHT(160))
    .leftEqualToView(fView)
    .heightIs(GETHEIGHT(100))
    .rightEqualToView(fView);
    
}

-(void)startTime{
    if(_userName.text.length<1){
        [AlertUtils showToastWithMessage:@"请先填写手机号码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        return;
        
    }else if (![ToolClass valiMobile:_userName.text]){
        [AlertUtils showToastWithMessage:@"请输入正确的手机号码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        return;
        
    }
    __weak typeof(self)weakself = self;
    
    [[PPHttpRequsetData shareInstance] requestStyle:Request_GET URL:@"/ShopApi/Login/sendVerify" parameter:@{@"phone":_userName.text	} successBlock:^(PPHttpRequest *request, id responseObj) {

        [weakself time];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
         [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:1.0 beIndeter:NO];
    } ];


}

- (void)time{
    _isSMSon = YES;
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置（倒计时结束后调用）
                [_hiddenON setTitle:@"重新发送" forState:UIControlStateNormal];
                //设置不可点击
                _hiddenON.userInteractionEnabled = YES;
                _hiddenON.backgroundColor = [UIColor whiteColor];
                _hiddenON.layer.borderColor = UIColorFromRGB(0xe64463).CGColor;
                [_hiddenON setTitleColor:UIColorFromRGB(0xe64463) forState:UIControlStateNormal];
                
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [_hiddenON setTitle:[NSString stringWithFormat:@"重新获取%@(s)",strTime] forState:UIControlStateNormal];
                //设置可点击
                _hiddenON.userInteractionEnabled = NO;
                _hiddenON.backgroundColor = [UIColor whiteColor];
                [_hiddenON setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                _hiddenON.layer.borderColor = [UIColor grayColor].CGColor;
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);

}

//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    if(endFrame.origin.y < (_password.bottom + 64) || endFrame.origin.y < (_userName.bottom+64)){
        [UIView animateWithDuration:0.25 animations:^{
            self.view.y = 0;
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            self.view.y = 64;
        }];
        
    }
    
    
}


- (void)ONLogin:(id)sender {
    [_password resignFirstResponder];
    [_userName resignFirstResponder];
    
    if(_userName.text.length<1){
        [AlertUtils showToastWithMessage:@"请先填写手机号码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        return;
    }
    if(_password.text.length<1){
        [AlertUtils showToastWithMessage:@"请先填写密码" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    
    if(![ToolClass valiMobile:_userName.text]){
        [AlertUtils showToastWithMessage:@"请填入正确的手机号" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    
    NSString *token = [userDefaults objectForKey:@"HLBdeviceToken"]?[userDefaults objectForKey:@"HLBdeviceToken"]:@"";
    
    [[PPHttpRequsetData shareInstance] requestStyle:Request_GET URL:@"/ShopApi/Login/login" parameter:@{@"phone":_userName.text,@"loginType":@"1",@"verifyCode":_password.text,@"deviceToken":token}successBlock:^(PPHttpRequest *request, id responseObj) {
        
        [userDefaults setObject:responseObj[@"guid"] forKey:@"guid"];
        [userDefaults setObject:responseObj[@"admin_id"] forKey:@"admin_id"];
        [userDefaults setObject:_userName.text forKey:@"useriPhone"];
        [[AppDelegate delegate] showMainCtr];

    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    } ];
    

}

- (void)clear:(id)sender {
    _password.text = @"";
    _userName.text = @"";
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if(textField == _password){
        if(_isSMSon == NO)
        {
            [textField resignFirstResponder];
            [AlertUtils showToastWithMessage:@"请先发送验证码" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
            return;
        }
    }
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    if(_password.text.length >0 || _userName.text.length > 0 ){
        [_login setBackgroundImage:[UIImage imageNamed:@"login_btn_defauit_hig"] forState:UIControlStateNormal];
       // _login.enabled = YES;
    }else{
        [_login setBackgroundImage:[UIImage imageNamed:@"login_btn_defauit_nor"] forState:UIControlStateNormal];
      //  _login.enabled = NO;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    return YES;
}

@end
